package com.rem.se.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author Rem
 * @date 2023/5/4
 */
public class BService {
    public static void main(String[] args) throws Exception {
        List<Integer> ids = new ArrayList<>();
        for (int i = 1; i <= 35; i++) {
            ids.add(i);
        }
        List<Integer> data = get(ids);
        System.out.println(data);
    }

    private static final int BATCH_SIZE = 10;
    private static final ExecutorService EXECUTOR = new ThreadPoolExecutor(4, 8, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024), new ThreadPoolExecutor.CallerRunsPolicy());

    public static List<Integer> get(List<Integer> ids) throws ExecutionException, InterruptedException {
        // 检查参数是否合法
        if (ids == null || ids.size() == 0 || ids.size() > 100) {
            throw new IllegalArgumentException("Invalid input");
        }
        // 将id列表分为若干批次，每批10个id
        List<List<Integer>> batches = new ArrayList<>();
        for (int i = 0; i < ids.size(); i += BATCH_SIZE) {
            int endIndex = Math.min(i + BATCH_SIZE, ids.size());
            batches.add(ids.subList(i, endIndex));
        }

        List<Integer> result = new ArrayList<>();
        for (List<Integer> batch : batches) {
            //考虑到如果业务复杂可以使用线程池
            Future<List<Integer>> future = EXECUTOR.submit(() -> AService.get(batch));
            result.addAll(future.get());
        }
        //关闭线程池，在容器中可以不用关闭
        EXECUTOR.shutdown();
        return result;
    }
}

class AService {
    public static List<Integer> get(List<Integer> ids) {
        // 在这里实现获取数据的逻辑,例如翻倍
        List<Integer> result = new ArrayList<>();
        for (Integer id : ids) {
            result.add(id * 2);
        }
        return result;
    }
}